<html>
<head>
<script type="text/javascript" src="gears_init.js"></script>
<script type="text/javascript" src="calgears.js"></script>
<script>
  var db;

  function load() {
    init();
    createStore();
    setupDatabase();
    if (localDatabase) {
      listEvents();
    }
  }

  function listEvents(root) {
    try {
      rs = localDatabase.execute("SELECT * FROM Events");
    } catch(e) {
      getEvents();
      return;
    }
    
    var events = [];
    var num = 0;

    while (rs.isValidRow()) {
      isPopulated = true;
      var evt = {};
      evt.title = rs.fieldByName('title');
      evt.date = rs.fieldByName('date');
      events[num] = evt;
      num++;
      rs.next();
    }
    rs.close();

    if (num == 0) {
      getEvents();
      return;
    } else {
      var html = [];
      html.push('<ul>');
      for (var i = 0; i < events.length; i++) {
        html.push('<li>', events[i].title, ': ', events[i].date, '</li>');
      }
      html.push('</ul>');
      document.getElementById("agenda").innerHTML = html.join("");
    }
  }
  
  function storeEvents(root) {
    var feed = root.feed;
    // Clear the events table in the local database
    if (localDatabase) {
      localDatabase.execute("DELETE FROM Events");
    }

    for (var i = 0; i < feed.entry.length; i++) {
      // push information into the database
      if (localDatabase) {
        var entry = feed.entry[i];
        var title = entry.title.$t;
        if (entry.gd$when) {
          var date = entry.gd$when[0].startTime;
        } else {
          var date = "N/A";
        }
	localDatabase.execute("INSERT INTO Events VALUES (?,?)", [title, date]);
      }
    }

    listEvents();
  }

  function getEvents() {
    var script = document.createElement("script");
    script.src = "http://www.google.com/calendar/feeds/pamela.fox%40gmail.com/public/full?alt=json-in-script&callback=storeEvents";
    document.body.appendChild(script);
  }

</script>
</head>
<body onload="load()">
<h3>Events:</h3>

<div id="agenda"></div>


<span id="textOut" style="color: red;"></span>
</body>
</html>
